#!/usr/bin/env python
# coding=utf-8

import os
import ID3
from optparse import OptionParser
from glob import glob
from PinyinConverter import PinyinConverter

fencs = ('utf-8', 'cp936', 'cp932', 'utf-16le', 'utf-16be')

# Oh! OO
class Mp3Info:
	pinyinConverter = PinyinConverter()
	def __init__(self, filepath):
		if not os.path.isfile(filepath):
			raise IOError("No such file or directory: '%s'" % (filepath))
		self.__fp = self._cvt2unicode(filepath)
		#self.__id3info = ID3.ID3(self.__fp)

	#def tag2utf8(self):
		#title_and_artist = self._get_tag()
		#self.__id3info.title = title_and_artist[0].encode('utf-8')
		#self.__id3info.artist = title_and_artist[1].encode('utf-8')

	def tag2pinyin(self):
		pass

	def filename2pinyin(self):
		folder, filename = os.path.split(self.__fp)
		pinyin = self.pinyinConverter.str2pinyin(filename)
		new_fp = os.path.join(folder, pinyin)
		os.rename(self.__fp, new_fp)
		self.__fp = new_fp

	def _cvt2unicode(self, s):
		for fenc in fencs:
			try:
				r = s.decode(fenc)
				return r
			except:
				pass
		raise UnicodeError()

	#def _get_tag(self):
		## return unicode
		#return [self._cvt2unicode(self.__id3info.title), self._cvt2unicode(self.__id3info.artist)]		

	def _get_filename(self):
		# return unicode
		pass

def parse_args():
	parser = OptionParser()
	parser.add_option('-t', '--mp3tag', action="store_true", dest="cvtMp3tag", default=False,
			help="Convert mp3tag to unicode")
	parser.add_option('-g', '--mp3tag2p', action="store_true", dest="cvtMp3tagPinyin", default=False,
			help="Convert mp3tag to pinyin")
	parser.add_option('-p', '--filename2p', action="store_true", dest="cvtFilenamePinyin", default=False,
			help="Convert filename to pinyin")
	parser.add_option('-f', '--files', action='append', dest='filenames',
			help="Given files to convert, support filename pattern", metavar="FILEs")
	(options, args) = parser.parse_args()
	return options

def process(opts):
	filenames = []
	if not opts.filenames:
		return
	for fpt in opts.filenames:
		filenames += glob(fpt)
	print(fpt)
	print(glob(fpt))
	print(filenames)
	for fn in filenames:
		print(fn)
		mp3info = Mp3Info(fn)
		#if opts.cvtMp3tag:
			#mp3info.tag2utf8()
		#if opts.cvtMp3tagPinyin:
			#mp3info.tag2pinyin()
		if opts.cvtFilenamePinyin:
			mp3info.filename2pinyin()


def main():
	opts = parse_args()
	process(opts)

if __name__ == '__main__':
	main()

